################################################################################
# Created By:Pietryka
# Creation Date:  2016-08-22
# Purpose: Create Figure 1, Bar plot of turnout using the CPS data
# Questions: mpietryka@fsu.edu
################################################################################

# PREAMBLE  ====================================



# LOAD PACKAGES --------------

library(tidyverse)


# LOAD DATA  --------------

# created in 'CPS-4A-Matching-Turnout.R'
load("Data/CPS-4A-Matching-Turnout.Rdata")




# COLORS
color_1 <- "darkslategray"
color_2 <- "orangered1"
color_grid <- "grey40"
color_annotate <- "grey40"



# FUNCTION  ----------------
bar_plot <- function(data) {
  ggplot(data, aes(y = estimate, x = lab, fill = lab, label = round(estimate, 2))) +
  geom_bar(stat = "identity",
           position = "dodge",
           colour = "black",
           alpha = .8) +
  xlab(NULL) +
  ylab(NULL) +
  expand_limits(y = .62) +
  facet_wrap( ~ year, strip.position = "bottom") +
  theme_minimal(base_size = 20) +
  theme(plot.subtitle = element_text(colour = color_annotate)) +
  theme(plot.caption = element_text(colour = color_annotate)) +
  theme(legend.position = "none") +
  geom_text(vjust = -.2, size = 7) +
  geom_text(aes(label = lab),
            y = 0.02,
            angle = 90,
            size = 10,
            hjust = 0,
            color = "white",
            fontface = "bold") +
  theme(axis.text.x = element_blank()) +
  theme(panel.grid.major.x = element_blank()) +
  #theme(panel.grid.major.y = element_line(colour = color_grid)) +
  scale_fill_manual(values = c(color_1, color_2))
}



# UNMATCHED ESTIMATES  ----------------

naive_bar <- cps_sub_10  %>%
  mutate(year = 2010)  %>%
  bind_rows(cps_sub_14)  %>%
  mutate(year = ifelse(is.na(year), 2014, year))  %>%
  group_by(year, prekkids)  %>%
  summarise(estimate = mean(turnout))  %>%
  na.omit()  %>%
  mutate(lab = ifelse(prekkids == 1, "Parents", "Non-Parents"))  %>%
  bar_plot() +
  ylab("Proportion Reporting Voting")



graphics.off()
windows(5, 6)
naive_bar


# MATCHED ESTIMATES  --------------
p0_10 <- sum(t(turnout_est_10$att.model)[, 1]  * c(1, 0))
p1_10 <- sum(t(turnout_est_10$att.model)[, 1]  * c(1, 1))
p0_14 <- sum(t(turnout_est_14$att.model)[, 1]  * c(1, 0))
p1_14 <- sum(t(turnout_est_14$att.model)[, 1]  * c(1, 1))





matched_bar <- tidyr::crossing(year = c(2010, 2014), prekkids = c(0, 1))  %>%
  mutate(estimate =
    ifelse(
      year == 2010,
      c(p0_10, p1_10),
      c(p0_14, p1_14)
      )
    )  %>%
  mutate(lab = ifelse(prekkids == 1, "Parents", "Non-Parents"))   %>%
  bar_plot()




graphics.off()
windows(5, 6)
matched_bar


# Save =======================================================

graphics.off()
windows(8, 6)
ggpubr::ggarrange(naive_bar, matched_bar,  align = "hv")
